package com.hellowx.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;


/**
 * Created by IntelliJ IDEA.
 *
 * @author MagicMushroom
 * @date 2021/6/30
 */
@RestController
@RequestMapping("/user")
public class UserController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping
    public String invokeDemo(){
        logger.info("user demo");

        // 1.使用spring内置对象RestTemplate发起请求
//        RestTemplate restTemplate = new RestTemplate();
//        String ret = restTemplate.getForObject("http://localhost:8901/order", String.class);

//        2.使用ribbon组件进行负载均衡
        // 1.DiscoveryClient
//        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("ORDER");
//        String ret1 = restTemplate.getForObject(serviceInstanceList.get(new Random().nextInt(serviceInstanceList.size())).getUri() + "/order", String.class);

        // 2.LoadBalanceClient
//        ServiceInstance serviceInstance = loadBalancerClient.choose("ORDER");
//        String ret2 = restTemplate.getForObject(serviceInstance.getUri() + "/order", String.class);

        // 3.@LoadBalance
        String ret = restTemplate.getForObject("http://ORDER/order", String.class);

        logger.info(ret);
        return "user demo!!";
    }
}
